package com.leo.leetcode.s100;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月21日
 */
public class T38CountAndSay {
    public static String countAndSay(int n) {
        String ans = "1";
        if (n == 1) return ans;
        for (int i = 2; i <= n; i++) {
            int j = 1;
            int count = 1;
            char tmp = ans.charAt(0);
            StringBuffer sb = new StringBuffer();
            while (j < ans.length()){
                if (ans.charAt(j) == tmp){
                    count++;
                }else {
                    sb.append(count).append(tmp);
                    tmp = ans.charAt(j);
                    count=1;
                }
                j++;
            }
            sb.append(count).append(tmp);
            ans = sb.toString();
        }
        return ans;
    }

    /**
     * 递归写法，无太大意义，还有栈溢出的风险
     * @param n
     * @return
     */
    public static String countAndSay2(int n) {
        if (n == 1){
            return "1";
        }else {
            String ans = countAndSay2(n-1);
            int j = 1;
            int count = 1;
            char tmp = ans.charAt(0);
            String tmpAns = "";
            while (j < ans.length()){
                if (ans.charAt(j) == tmp){
                    count++;
                }else {
                    tmpAns+= ""+count+tmp;
                    tmp = ans.charAt(j);
                    count=1;
                }
                j++;
            }
            tmpAns+= ""+ count+tmp;
            ans = tmpAns;
            return ans;
        }
    }

    public static void main(String[] args) {
        System.out.println(countAndSay(1));
        System.out.println(countAndSay(2));
        System.out.println(countAndSay(3));
        System.out.println(countAndSay(4));
        System.out.println(countAndSay(5));
        System.out.println(countAndSay(6));
    }
}
